package summary;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/16 10:31
 * https://leetcode-cn.com/problems/combination-sum/
 */
public class Title39 {

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> list = new LinkedList<>();
    int sum = 0;

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates.length == 1 && candidates[0] != target) {
            return result;
        }
        Arrays.sort(candidates);
        backTracking(candidates, target, 0);
        return result;
    }

    private void backTracking(int[] candidates, int target, int start) {
        if (sum >= target) {
            if (sum == target) {
                result.add(new ArrayList<>(list));
            }
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            list.offer(candidates[i]);
            sum += candidates[i];
            backTracking(candidates, target, i);
            list.removeLast();
            sum -= candidates[i];
        }
    }


    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> temp = new LinkedList<>();
        backTracking1(result, temp, candidates,  target,0);
        return result;
    }

    private void backTracking1(List<List<Integer>> result, LinkedList<Integer> temp, int[] candidates, int target, int cur) {
        if (0 == target) {
            result.add(new ArrayList<>(temp));
            return;
        }
        for (int i = cur; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                continue;
            }
            temp.add(candidates[i]);
            backTracking1(result, temp, candidates, target - candidates[i], i);
            temp.removeLast();
        }
    }

    public static void main(String[] args) {

    }
}
